<script>
import RunningTime from '@/common/runningTime'
import echarts from 'echarts'
import { mapState } from 'vuex'
import { getHomeInfos, getHomeTrend } from 'services/x-start/mgr/common'
import navList from './navLIst'
import trenList from './trenList'
import formatter from './formatter'

export default {
  components: { RunningTime },
  data() {
    return {
      dataType: ['本月', '本周', '今日'],
      homeInfo: {
        persion: {},
        trend: [],
        count: {},
        trenInfo: {},
        totalData: {},
        totalInfo: {},
      },
      navList,
      trenList,
      sportType: '',
      daysAgo: '7',
      currentDate: new Date(),
      week: null,
      charts1: null,
      charts2: null,
    }
  },
  computed: {
    ...mapState({
      typeList: state => {
        return state.sportList
      },
    }),
  },
  mounted() {
    window.onresize = () => {
      this.charts1 && this.charts1.resize()
      this.charts2 && this.charts2.resize()
    }
  },
  created() {
    this.week = this.getWeek()
    this.getHomeInfos()
  },
  methods: {
    update(to) {
      this.getHomeInfos(to && to.params && to.params.id)
    },
    getHomeInfos(id) {
      getHomeInfos({
        type: this.sportType,
        date: this.currentDate,
        daysAgo: this.daysAgo,
      })
        .then(res => {
          this.homeInfo = res
          const { count, trenInfo } = res
          console.log(res.totalInfo, 1111)
          this.formatTrenList(trenInfo)
          this.navList[0].num = count && count.todayEntNum
          this.navList[2].num = count && count.saturability
          this.init()
        })
        // .catch(({ err: payload }) => {
        .catch(err => {
          console.log(err)
          // this.$message.error(payload && payload.msg)
        })
    },
    formatTrenList(trenInfo) {
      this.trenList.forEach(item => {
        for (const key in trenInfo) {
          if (trenInfo.hasOwnProperty(key)) {
            const element = trenInfo[key]
            if (item.type == key) {
              item.num = element
            }
          }
        }
      })
    },
    init() {
      this.draw({
        ref: 'charts1',
        x: Object.keys(this.homeInfo.persion),
        y: Object.values(this.homeInfo.persion),
        type: 'bar',
      })
      this.drawCharts2()
      this.drawGauge()
    },
    drawCharts2() {
      this.draw({
        ref: 'charts2',
        x: this.homeInfo.trend.map(item => item.resultKey),
        y: this.homeInfo.trend.map(item => item.resultValue),
      })
    },
    draw({ ref, name = '', x = [], y = [], type = 'line' }) {
      this[ref] = echarts.init(this.$refs[ref])
      this[ref].setOption({
        title: {
          text: name,
          x: 'center',
        },
        color: ['#4472C4'],
        tooltip: {
          trigger: 'axis',
        },
        grid: {
          x: 40,
          y: 10,
          x2: 30,
          y2: 40,
        },
        xAxis: {
          type: 'category',
          data: x,
          axisLabel: {
            interval: 0,
            rotate: this.daysAgo == '30' ? -40 : 0,
            formatter,
          },
          axisLine: {
            lineStyle: {
              color: '#999', // 颜色
            },
          },
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: y,
            type: type,
            // smooth: true,//曲线
            barWidth: 20,
            itemStyle: {
              emphasis: {
                barBorderRadius: 25,
              },
              normal: {
                barBorderRadius: 25,
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#feaea2' },
                  { offset: 1, color: '#fd7270' },
                ]),
              },
            },
          },
        ],
      })
    },
    drawGauge() {
      let dom = echarts.init(this.$refs.charts0)
      console.log(this.homeInfo.totalData)
      dom.setOption({
        title: {
          text: '区域运动人次占比',
          left: 'left',
          textStyle: {
            color: '#ff6d60',
            fontSize: '16',
            fontWeight: 'normal',
          },
        },
        grid: {
          top: 40,
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          icon: 'circle', //  字段控制形状  类型包括 circle，rect,line，roundRect，triangle，diamond，pin，arrow，none
          itemWidth: 15, // 设置宽度
          itemHeight: 15, // 设置高度
          top: 20,
          right: 10,
          data: this.homeInfo.totalData.map(item => item.name),
        },
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: ['30%', '50%'],
            center: ['35%', '53%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center',
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: '30',
                  fontWeight: 'bold',
                },
              },
            },
            labelLine: {
              normal: {
                show: false,
              },
            },
            data: this.homeInfo.totalData,
            label: {
              normal: {
                position: 'inner',
                formatter: '{d}%',
              },
            },
          },
        ],
      })
    },
    change(v) {
      if (v) {
        this.week = this.getWeek(v)
        this.getHomeInfos()
      }
    },
    getWeek(data = new Date()) {
      let changeNum = [
        '零',
        '一',
        '二',
        '三',
        '四',
        '五',
        '六',
        '七',
        '八',
        '九',
      ]
      let time
      if (typeof data == 'string') {
        time = new Date(data).getDay()
      } else {
        time = data.getDay()
      }
      if (time === 0) {
        return '星期天'
      } else {
        return '星期' + changeNum[time]
      }
    },
    changeTrend(day) {
      this.daysAgo = day
      this.getHomeTrend()
    },
    getHomeTrend() {
      getHomeTrend({
        type: this.sportType,
        date: this.currentDate,
        daysAgo: this.daysAgo,
      }).then(({ trenInfo, trendData }) => {
        this.homeInfo.trend = trendData
        this.formatTrenList(trenInfo)
        this.drawCharts2()
      })
    },
    getCompany(key) {
      switch (key) {
        case '总数据量':
          return '条'
          break
        case '总服务时长':
          return '小时'
          break
        case '总累计客流量':
          return '人次'
          break
        default:
          return '人次'
          break
      }
    },
  },
  watch: {
    typeList: {
      handler() {
        this.navList[1].num = this.typeList.length
      },
      immediate: true,
    },
    sportType() {
      this.getHomeTrend()
    },
  },
}
</script>

<template lang="pug">
.div
  .top-nav
    el-date-picker(
      v-model="currentDate"
      type="date"
      value-format="yyyy-MM-dd"
      placeholder="选择日期"
      :editable="false"
      prefix-icon="icon-menu-rili"
      :clearable="false"
      @change="change"
    )
    span |
    | 
    p.week {{week}}
  .mainRight
    .content
      .top
        .warehouse
          .title.icon.icon-menu-title 客流总览
          ul.nav
            li.item(v-for="item in navList" )
              .cont
                p.name {{item.name}}
                p.num(:style="{color:item.color}")
                  span.sup {{item.num}}
                  | 
                  span.sub {{item.site}}
          .draw(ref="charts1")
      .bottom
        .left
          .warehouse
            .title.icon.icon-menu-title 运动人数趋势
            ul.nav
              li.item(v-for="item in trenList" )
                .cont
                  p.name {{item.name}}
                  p.num(:style="{color:item.color}")
                    span.sup {{item.num}}
                    | 
                    span.sub {{item.site}}
            .navTilte
              .group
                label 数据分类：
                el-select(v-model="sportType" clearable placeholder="全部" size="mini")
                  el-option(v-for="item in typeList"
                    :key="item.sportName"
                    :label="item.sportName"
                    :value="item.id"
                  )
              .group
                el-button(size="mini" type="primary" @click="changeTrend('7')" :plain="daysAgo!='7'") 近7天
                el-button(size="mini" type="primary" @click="changeTrend('30')" :plain="daysAgo!='30'") 近30天
            .draw(ref="charts2")
        .right
          .warehouse
            .title.icon.icon-menu-title 总体数据
            .box
              .text
                .item(v-for="item,key,index in homeInfo.totalInfo" :class="'item_'+index")
                  .tit {{key}}
                  .num
                    span.sup {{item}}
                    | 
                    span.sub {{getCompany(key)}}
              .draw3(ref="charts0")
</template>
<style lang="stylus" scoped>
@import './index.styl'
</style>
